import 'dart:convert';

import 'package:base_flutter/base_flutter.dart';
import 'package:dio/dio.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:ls_work/a_message/models/message_section_entity.dart';
import 'package:ls_work/a_message/page/message_row_page.dart';
import 'package:ls_work/a_message/views/message_section_view.dart';
import 'package:ls_work/mvp/svp_progress.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/res/gaps.dart';
import 'package:ls_work/res/styles.dart';
import 'package:ls_work/util/app_navigator.dart';
import 'package:ls_work/util/toast.dart';

class MallPage extends StatefulWidget {
  @override
  _MallPageState createState() => _MallPageState();
}

class _MallPageState extends State<MallPage>
    with AutomaticKeepAliveClientMixin<MallPage> {
  @override
  bool get wantKeepAlive => true;

  int _page = 1;
  List<MessageSectionInfo> dataList = [];
  EasyRefreshController _controller = EasyRefreshController();

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _messageSectionList();
    });
    super.initState();
    eventBus.on<SendMessageEvent>().listen((event) {
      if(event.msgCode==100){
        _controller.callRefresh();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: AppBar(
        title: Text('消息'),
        elevation: 0.5,
      ),
      body: EasyRefresh(
        header: MaterialHeader(),
        footer: MaterialFooter(),
        enableControlFinishLoad: true,
        onRefresh: _onRefresh,
        onLoad: _loadMore,
        controller: _controller,
        child: dataList.length > 0
            ? ListView.separated(
                itemCount: dataList.length,
                itemBuilder: (context, index) {
                  return GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: () {
                      AppNavigator.push(
                        context,
                        MessageRowPage(
                          info: dataList[index],
                        ),
                      );
                      setState(() {
                        dataList[index].unreadCount = 0;
                      });
                    },
                    child: MessageSectionView(
                      info: dataList[index],
                    ),
                  );
                },
                separatorBuilder: (context, index) => Gaps.line,
              )
            : SizedBox(
                height: ScreenUtil.getScreenH(context),
                child: Center(
                  child: Text(
                    '暂无数据',
                    style: TextStyles.textGray14,
                  ),
                ),
              ),
      ),
    );
  }

  Future _onRefresh() async {
    _page = 1;
    await await _messageSectionList();
  }

  Future _loadMore() async {
    _page++;
    await _messageSectionList();
  }

  ///城市机构详情信息
  _messageSectionList() async {
    var map = {"rows": 10};
    if (_page > 1) map['page'] = _page;

    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post(HttpApi.messageSectionUrl, data: map)
        .then((r) {
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          MessageSectionEntity model =
              MessageSectionEntity.fromJson(map['data']);
          var tempArr = model.rows;
          setState(() {
            if (_page == 1) {
              dataList = [];
              dataList = model.rows??[];
            } else {
              dataList += (tempArr??[]);
            }
            _controller.finishLoad(
                success: true, noMore: (model.rows??[]).length != 10);
          });
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print('🦊' + e.toString());
      Toast.show(getErrorMessage(e));
    });
  }
}
